#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2023/12/7 15:33
# @Author : 杨凯锐

from multiprocessing import Pool
import os
import sys
from xml.etree import ElementTree

__path_temp = None

if __name__ == '__main__':
    do_pool()

def do_pool():
    """
    通过进程池执行任务
    进程池默认大小为10,可通过修改配置文件改变
    :return:
    """
    # 设置默认进程池大小为10
    pool_size = 10

    # 获取配置文件路径
    for path in sys.path:
        __find_file(path, 'config.xml')
        if not (__path_temp is None):
            break
    if __path_temp is None:
        raise FileNotFoundError('No such *config.xml!')

    # 读取配置文件
    root = __read_xml(__path_temp)

    # 读取配置文件中进程池大小
    pool_size_config = root.find('./options/pool_size')
    # 如果配置文件内进程池不为空则以配置文件中值为准
    if not (pool_size_config is None):
        pool_size = int(pool_size_config.text)

    # 读取要执行的任务
    tasks = root.find('./tasks')
    if tasks is None:
        raise ValueError('No Task!')
    # 开启进程池
    pool = Pool(pool_size)
    # 遍历任务
    for task in tasks:
        # 是否执行任务
        flag = True
        if task is None:
            raise ValueError('No Task!')

        task_class = task.find('task_class')
        task_package = task.find('task_package')

        if task_class is None:
            print('task_class is None!')
            flag = False
        if task_package is None:
            print('task_package is None!')
            flag = False

        if flag:
            # 执行任务
            pool.apply_async(func=__execute, args=(task_class.text, task_package.text,))

    pool.close()
    pool.join()
